<template>
  <div class="page-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          :inline="true"
          label-position="left"
          @submit.prevent
        >
          <el-form-item :label="$t('dept.name')">
            <el-input v-model="queryParams.deptName" :placeholder="$t('dept.nameTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('status')">
            <el-select v-model="queryParams.status" :placeholder="$t('select')" clearable @keyup.enter.native="handleQuery" style="width: 140px;">
              <el-option :label="$t('enabled')" value="1" />
              <el-option :label="$t('disabled')" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('createTime')">
            <el-date-picker
              v-model="queryParams.createTime"
              type="daterange"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{$t('query')}}</el-button>
            <el-button @click="reset">{{$t('reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div class="tool-controls">
      <el-button type="primary" plain :icon="Plus" @click="handleAdd">{{$t('add')}}</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="lists"
      :border="true"
      row-key="deptId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column :label="$t('dept.name')" prop="deptName" />
      <el-table-column :label="$t('dept.leader')" align="center" prop="leader" width="120" />
      <el-table-column :label="$t('dept.phone')" align="center" prop="phone" width="120" />
      <el-table-column :label="$t('dept.email')" align="center" prop="email" width="160" />
      <el-table-column :label="$t('sort')" align="center" prop="orderNum" width="100" />
      <el-table-column :label="$t('status')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-text v-if="scope.row.status == '1'" type="success">{{$t('enabled')}}</el-text>
          <el-text v-else type="danger">{{$t('disabled')}}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="180" :formatter="formatterTime" />
      <el-table-column :label="$t('handle')" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">{{$t('edit')}}</el-button>
          <el-button v-if="scope.row.parentId != 0" type="text" size="small" @click="handleDelete(scope.row)">{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="lists.length > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="lists.length"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>

  <!--新增修改-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="460px">
    <el-form ref="userForm" :model="deptInfo" :rules="rules" label-width="auto">
      <el-form-item :label="$t('dept.parentDept')" prop="parentId" v-if="deptInfo.parentId != 0">
        <el-tree-select
          v-model="deptInfo.parentId"
          :data="treeData"
          :render-after-expand="false"
          :check-strictly="true"
          :props="{ value: 'deptId', label: 'deptName'}"
          value-key="deptId"
          node-key="deptId"
        />
      </el-form-item>
      <el-form-item :label="$t('dept.name')" prop="deptName">
        <el-input v-model="deptInfo.deptName" :placeholder="$t('dept.nameTip')" />
      </el-form-item>
      <el-form-item :label="$t('dept.leader')" prop="leader">
        <el-input v-model="deptInfo.leader" :placeholder="$t('dept.leaderTip')" />
      </el-form-item>
      <el-form-item :label="$t('dept.phone')" prop="phone">
        <el-input v-model="deptInfo.phone" :placeholder="$t('dept.phoneTip')" />
      </el-form-item>
      <el-form-item :label="$t('dept.email')" prop="email">
        <el-input v-model="deptInfo.email" :placeholder="$t('dept.emailTip')" />
      </el-form-item>
      <el-form-item :label="$t('sort')" prop="orderNum">
        <el-input-number v-model="deptInfo.orderNum" :min="0" />
      </el-form-item>
      <el-form-item :label="$t('status')" prop="status">
        <el-radio-group v-model="deptInfo.status">
          <el-radio label="1">{{$t('enabled')}}</el-radio>
          <el-radio label="0">{{$t('disabled')}}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t('confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from '#imports';
import { useI18n } from '#imports';
import type { FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import dayjs from 'dayjs';

const { t } = useI18n();

definePageMeta({
  title: '部门管理',
  en_title: 'Department Management',
})

interface QueryParams {
  deptName: string;
  status: string;
  createTime: Array<string>;
}

interface DeptModel {
  deptId?: string;
  parentId: number,
  ancestors: string,
  deptName: string;
  status: string;
  orderNum: number;
  leader?: string;
  phone?: string;
  email?: string;
}

const queryParams: Ref<QueryParams> = ref({
  deptName: '',
  status: '',
  createTime: [],
})

const handleQuery = () => {
  currentPage.value = 1;
  getLists();
}

const reset = () => {
  queryParams.value = {
    deptName: '',
    status: '',
    createTime: [],
  }
}

const dialogVisible = ref(false);
const deptInfo: Ref<DeptModel> = ref({
  deptId: '',
  parentId: 1,
  ancestors: '1',
  deptName: '',
  status: '1',
  orderNum: 0,
  leader: '',
  phone: '',
  email: '',
});
const rules = reactive<FormRules>({
  parentId: [{ required: true, message: t('dept.pearentDeptTip'), trigger: 'blur' }],
  deptName: [{ required: true, message: t('dept.nameTip'), trigger: 'blur' }],
  status: [{ required: true, message: t('select'), trigger: 'change' }],
})
const dialogTitle = ref('');
const operateType = ref('');
const handleAdd = () => {
  dialogVisible.value = true;
  operateType.value = 'add';
  dialogTitle.value = t('add');
  deptInfo.value = {
    parentId: 1,
    ancestors: '1',
    deptName: '',
    status: '1',
    orderNum: 0,
    leader: '',
    phone: '',
    email: '',
  }
}

const handleEdit = (row: DeptModel) => {
  dialogVisible.value = true;
  operateType.value = 'edit';
  dialogTitle.value = t('edit');
  deptInfo.value = row;
}

const submitForm = async () => {
  deptInfo.value.ancestors = getNodeAncestors();
  if (operateType.value === 'add') {
    const result: any = await deptCreate(deptInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('addSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  } else if (operateType.value === 'edit') {
    const result: any = await deptUpdate(deptInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('updateSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  }
}

const handleDelete = (row: DeptModel) => {
  ElMessageBox.confirm(t('confirmDelete'), t('prompt'), {
    confirmButtonText: t('confirm'),
    cancelButtonText: t('cancel'),
    type: 'warning',
  }).then(async () => {
    const result: any = await deptDelete({ deptId: row.deptId });
    if (result?.code === 200) {
      ElMessage.success(t('deleteSuccess'));
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  })
}

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const lists: Ref = ref([]);
const getLists = async () => {
  loading.value = true;
  const params: {
    page: number;
    pageSize: number;
    deptName?: string;
    status?: string;
    startTime?: string;
    endTime?: string;
  } = {
    page: currentPage.value,
    pageSize: pageSize.value,
  }
  
  const { deptName, status, createTime } = queryParams.value;
  deptName && (params.deptName = deptName);
  status && (params.status = status);
  if (createTime && createTime.length > 0) {
    params.startTime = dayjs(createTime[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(createTime[1]).format('YYYY-MM-DD');
  }

  const result: any = await queryDepts(params);
  if (result?.code === 200) {
    lists.value = toTree(result.data, 'deptId', 'parentId');
  }
  loading.value = false;
}
getLists();

const treeData: Ref = ref([]);
const getTreeData = async () => {
  const result: any = await queryAllDepts();
  if (result?.code === 200) {
    treeData.value = toTree(result.data, 'deptId', 'parentId');
  }
}
getTreeData();

const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  getLists();
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getLists();
}

const formatterTime = (data : any) => {
  return formatDate(data.createTime, 'YYYY-MM-DD HH:mm:ss');
}

const getNodeAncestors = () => {
  const tree = fromatDeptTree(treeData.value);
  let data: any = tree.find((item) => item.deptId === deptInfo.value.deptId);
  const result: number[] = [];
  
  while (true) {
    result.unshift(data.deptId);
    if (data?.parent) {
      data = data.parent;
    } else {
      break;
    }
  }
  result.unshift(0);
  
  return result.slice(0, -1).join(',')
}

const fromatDeptTree = (data: any) => {
  const results: any[] = [];

  const traverse = (data: any[], parent: any = null) => {
    data.forEach((item) => {
      const result = {
        ...item,
        parent,
      }
      results.push(result);
      if (item.children && item.children.length > 0) {
        traverse(item.children, result);
      }
    });
  };

  traverse(data);

  return results;
}
</script>